package com.haoziqi.demo;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;

/**
 * description
 * created by A on 2022/5/7
 */
public class Test1 {
    public static void main(String[] args) throws IOException {
        HttpServerProvider provider = HttpServerProvider.provider();
        HttpServer httpserver =provider.createHttpServer(new InetSocketAddress(9999), 100);//监听端口19017,能同时接受100个请求
        //监听的地址，如果是用/，表示向该端口发送的所有地址都会被监听
        httpserver.createContext("/", new MyResponseHandler());
        //设置请求的线程执行器, 设置为 null 表示使用默认的执行器，封装了http请求和响应的所有数据操作
        httpserver.setExecutor(null);
        httpserver.start();
        System.out.println("server started");
    }
    public static class MyResponseHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException {
            System.out.println("receive");
            //获得请求方法
            String requestMethod = httpExchange.getRequestMethod();
            System.out.println("------"+requestMethod+"-------------");
            if (requestMethod.equalsIgnoreCase("GET")) {//客户端的请求是get方法
                //设置服务端响应的编码格式，否则在客户端收到的可能是乱码
                Headers responseHeaders = httpExchange.getResponseHeaders();
                responseHeaders.set("Content-Type", "text/html;charset=utf-8");

                //在这里通过httpExchange获取客户端发送过来的消息
                //URI url = httpExchange.getRequestURI();
                InputStream requestBody = httpExchange.getRequestBody();
                String s = readStream(requestBody);
                System.out.println(s);
                String response = "请求返回";

                httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes("UTF-8").length);

                OutputStream responseBody = httpExchange.getResponseBody();
                OutputStreamWriter writer = new OutputStreamWriter(responseBody, "UTF-8");
                writer.write(response);
                writer.close();
                responseBody.close();
            }

        }
    }


    /**
     * 读取 InputStream 到 String字符串中
     */
    public static String readStream(InputStream in) {
        try {
            //<1>创建字节数组输出流，用来输出读取到的内容
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //<2>创建缓存大小
            byte[] buffer = new byte[1024]; // 1KB
            //每次读取到内容的长度
            int len = -1;
            //<3>开始读取输入流中的内容
            while ((len = in.read(buffer)) != -1) { //当等于-1说明没有数据可以读取了
                baos.write(buffer, 0, len);   //把读取到的内容写到输出流中
            }
            //<4> 把字节数组转换为字符串
            String content = baos.toString();
            //<5>关闭输入流和输出流
            in.close();
            baos.close();
            //<6>返回字符串结果
            return content;
        } catch (Exception e) {
            e.printStackTrace();
            return  e.getMessage();
        }
    }
}
